package klog

import (
	"fmt"
	"os"
	"sync"
	"time"
)

type Logger interface {
	Debugf(format string, a ...interface{})
	Infof(format string, a ...interface{})
	Warnf(format string, a ...interface{})
	Errorf(format string, a ...interface{})
}

const (
	LevelDebug int = 1
	LevelInfo  int = 2
	LevelWarn  int = 3
	LevelError int = 4
)

type stdOutLogger struct {
	level int
}

var mutex = sync.Mutex{}
var l Logger

// GetStdLogger 获取 logger 单例
func GetStdLogger(level int) Logger {
	mutex.Lock()
	defer mutex.Unlock()
	if l == nil {
		l = &stdOutLogger{level: level}
	}
	return l
}

func (o *stdOutLogger) print(levelString, format string, a ...interface{}) {
	timeString := time.Now().In(BeijingZone).Format("2006-01-02T15:04:05.000+0800")
	extendedFormat := fmt.Sprintf("%s %s %s\n", timeString, levelString, format)
	_, _ = fmt.Fprintf(os.Stdout, extendedFormat, a...)
}

func (o *stdOutLogger) Debugf(format string, a ...interface{}) {
	if o.level == LevelDebug {
		o.print("DEBUG", format, a...)
	}
}

func (o *stdOutLogger) Infof(format string, a ...interface{}) {
	if o.level <= LevelInfo {
		o.print("INFO", format, a...)
	}
}

func (o *stdOutLogger) Warnf(format string, a ...interface{}) {
	if o.level <= LevelWarn {
		o.print("WARN", format, a...)
	}
}

func (o *stdOutLogger) Errorf(format string, a ...interface{}) {
	if o.level <= LevelError {
		o.print("ERROR", format, a...)
	}
}
